#include <ctype.h>
#include <getopt.h>
#include <stdio.h>
#include <stdlib.h>
#include <assert.h>
#include "buf.h"
#include "bson.h"

static buf_t buffer;
static buf_t output;
static buf_t error;

int
main(int argc, char **argv) {
  int c;
  char *in_name = NULL, *out_name = NULL;
  FILE *in = stdin, *out = stdout;
  int result;

  do {
    switch ((c = getopt(argc, argv, "f:o:"))) {
    case -1:
      goto done;
    case 'f':
      in_name = optarg;
      break;
    case 'o':
      out_name = optarg;
      break;
    case '?':
      return 1;
    default:
      abort();
    }
  } while (!0);
 done:

  if (in_name) {
    if (!(in = fopen(in_name, "r"))) {
      fprintf(stderr, "File %s does not exist.\n", in_name);
      return 1;
    }
  }

  buf_acquire(&output);
  buf_acquire(&error);
  buf_acquire(&buffer);
  result = bson_compile_file(in, &buffer, &output, &error);
  buf_release(&buffer);
  fclose(in);
  switch (result) {
  case 0:
    if (out_name) {
      if (!(out = fopen(out_name, "w"))) {
	fprintf(stderr, "Error creating file %s.\n", out_name);
	result = 1;
	break;
      }
    }
    fwrite(buf_elems(&output), 1, buf_size(&output), out);
    fclose(out);
    break;
  case 1:
  case 2:
    fwrite(buf_elems(&error), 1, buf_size(&error), stderr);
    fputc('\n', stderr);
    break;
  default:
    assert(0);
  }
  buf_release(&error);
  buf_release(&output);
  return result;
}
